package com.yw.atp.util;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Map;
import ognl.DefaultTypeConverter;

public class DateConverter extends DefaultTypeConverter{	
	  public Object convertValue(Map ognlContext, Object value,Class toType){
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		if(value!=null){
			String[] strs;
			try{
				strs = (String[])value;
			}catch(Exception e){
				strs = null;
			}
			if(strs!=null&&strs[0]!=null){
				if( toType == java.util.Date.class ) {
				      try {
						  return getRealDate(sdf.parse(strs[0]));
					  } catch (ParseException e) {
						  try{
							  sdf = new SimpleDateFormat("yyyy/MM/dd");
							  return getRealDate(sdf.parse(strs[0]));
						  }catch(Exception ex){
							  try{
								  sdf = new SimpleDateFormat("MM/dd HH:mm");
								  return getRealDateB(sdf.parse(strs[0]));
							  }catch(Exception exc){
								  return null;
							  }
						  }
					  }
				}else if( toType == String.class ) {
					  return String.valueOf(strs[0]);
				}
			}
		}  
	    return null;
	  }
	  
	  public static Date getRealDate(Date date){
		  Calendar cal = Calendar.getInstance();
		  Calendar c = Calendar.getInstance();
		  c.setTime(date);
		  c.set(Calendar.HOUR_OF_DAY,cal.get(Calendar.HOUR_OF_DAY));
		  c.set(Calendar.MINUTE,cal.get(Calendar.MINUTE));
		  c.set(Calendar.SECOND,cal.get(Calendar.SECOND));
		  return c.getTime();
	  }
	  
	  public static Date getRealDateB(Date date){
		  Calendar cal = Calendar.getInstance();
		  Calendar c = Calendar.getInstance();
		  c.setTime(date);
		  c.set(Calendar.YEAR,cal.get(Calendar.YEAR));
		  return c.getTime();
	  }
	  
}
